import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:laos_mall/common/style/app_style.dart';
import 'package:laos_mall/common/style/extension_util.dart';
import 'package:laos_mall/common/utils/http_util.dart';
import 'package:laos_mall/models/config/area_code_model.dart';

class CityDataPicker extends StatefulWidget {
   CityDataPicker({super.key, required this.dataSource,this.callBack});
  final List<CityAreaModel> dataSource;
   Function(CityAreaModel? modle,{List<CityAreaModel?>? models})? callBack;
  @override
  State<CityDataPicker> createState() => _CityDataPickerState();
}

class _CityDataPickerState extends State<CityDataPicker> {
  late List<CityAreaModel> regionList;

  int selectedLevel1Index = 0;
  int selectedLevel2Index = 0;
  int selectedLevel3Index = 0;

  @override
  void initState() {
    regionList = widget.dataSource;
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return  Column(
        // mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(children: [
            AppButton.sizeBtn(() {
              Get.back();
            }, Text("cancel".tr,style: AppStyle.textStyleLightGray,),style: AppButtonStyle.textBtn,width: 70,),
            Spacer(),
            AppButton.sizeBtn(() {
              var res = regionList[selectedLevel1Index].children?[selectedLevel2Index]?.children?[selectedLevel3Index];
              var  address1 = regionList[selectedLevel1Index];
              var  address2 = regionList[selectedLevel1Index].children?[selectedLevel2Index];
              widget.callBack?.call(res,models: [address1,address2,res]);
              Get.back(result: res);
            }, Text("confirm".tr,style: AppStyle.textStyle,),style: AppButtonStyle.textBtn,width: 80),
          ],),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 第一级选择器
              buildListWheelScrollView(0),
              // 第二级选择器
              buildListWheelScrollView(1),
              // 第三级选择器
              buildListWheelScrollView(2),
            ],
          ),
          SizedBox(height: 37),
        ]
    ).addContainer();
  }

  // 构建 ListWheelScrollView 组件
  Widget buildListWheelScrollView(int level) {
    List<CityAreaModel?>? cities= [];
    int selIndex = 0;
    switch(level){
      case 0:
        cities = widget.dataSource;
        selIndex = selectedLevel1Index;
        break;
      case 1:
        cities = widget.dataSource[selectedLevel1Index].children ;
        selIndex = selectedLevel2Index;
        break;
      case 2:
        cities = widget.dataSource[selectedLevel1Index].children?[selectedLevel2Index]?.children ;
        selIndex = selectedLevel3Index;
        break;
    }

    return Container(
      width: 100,
      height: 160,
      color: Colors.transparent,
      child: ListWheelScrollView.useDelegate(
        itemExtent: 40,
        useMagnifier: true,
        physics:FixedExtentScrollPhysics(),
        childDelegate: ListWheelChildBuilderDelegate(
          builder: (context, index) {

            bool isSel = selIndex == index ? true : false;
            return Text(cities?[index]?.regionName ?? "--",style:  AppStyle.textStyle.copyWith(color:isSel ? AppColor.primaryColor: AppColor.textColor2),).addContainer(width: 100,color: Colors.transparent,alignment: Alignment.center);
          },
          childCount: cities?.length,

        ),
        onSelectedItemChanged: (index){
          if(level == 0){
            selectedLevel1Index = index;
            selectedLevel2Index = 0;
            selectedLevel3Index = 0;
          }else if(level == 1){
            selectedLevel2Index = index;
            selectedLevel3Index = 0;
          }else{
            selectedLevel3Index = index;
          }
          setState(() {

          });

        },
      ),
    );
  }

  // 获取选择的区域信息
  String getSelectedRegion() {
    return "选择的地址";
    // return "${regionList[0][selectedLevel1Index]["region_name"]} - ${regionList[1][selectedLevel2Index]["region_name"]} - ${regionList[2][selectedLevel3Index]["region_name"]}";
  }



}

class CityAreaModel {
  bool? leaf;
  int? regionId;
  int? level;
  String? regionName;
  int? parentId;
  int? isHot;
  String? firstWord;
  List<CityAreaModel?>? children;

  CityAreaModel(
      {this.leaf,
        this.regionId,
        this.level,
        this.regionName,
        this.parentId,
        this.isHot,
        this.firstWord,
        this.children});

  CityAreaModel.fromJson(Map<String, dynamic> json) {
    leaf = json['leaf'];
    regionId = json['region_id'];
    level = json['level'];
    regionName = json['region_name'];
    parentId = json['parent_id'];
    isHot = json['is_hot'];
    firstWord = json['first_word'];
    if (json['children'] != null) {
      children = [];
      json['children'].forEach((v) {
        children?.add(CityAreaModel.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['leaf'] = leaf;
    data['region_id'] = regionId;
    data['level'] = level;
    data['region_name'] = regionName;
    data['parent_id'] = parentId;
    data['is_hot'] = isHot;
    data['first_word'] = firstWord;
    if (children != null) {
      data['children'] = children?.map((v) => v?.toJson()).toList();
    }
    return data;
  }
}



class CityDataPickerUtil{

  static void show(context,{Function(CityAreaModel? modle,{List<CityAreaModel?>? models})? callBack}) async{
    var res =  await HttpUtil.restApi.getRegionTree({});
    var data = res.data["region_list"] as List<dynamic>;
    var models = data.map((e) => CityAreaModel.fromJson(e)).toList();
     var area = await Get.bottomSheet<CityAreaModel?>(CityDataPicker(dataSource: models,callBack: callBack));

  }
}


